package com.ricohgag.controller.common;

import com.alibaba.fastjson.JSON;
import com.ricohgag.util.CodeUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ricohgag
 * @date 2018/9/4 11:48
 */
@Controller
@RequestMapping("/common")
public class CodeController {
    /**
     * ajax通过工具类CodeUtil得到验证码
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/code")
    @ResponseBody
    public void getCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
        int width = 95;
        int height = 45;

        String codeStr = CodeUtil.getCodeString();
        HttpSession session = request.getSession();
        //存入session
        session.setAttribute("codeStr", codeStr);

        BufferedImage buffImg = new BufferedImage(width, height, 1);
        Graphics2D graphics = buffImg.createGraphics();
        graphics.setColor(Color.WHITE);
        graphics.setFont(new Font("微软雅黑", Font.BOLD, 24));
        graphics.drawString(codeStr, 10, 30);

        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        OutputStream sos = response.getOutputStream();
        ImageIO.write(buffImg, "jpeg", sos);
        sos.flush();
        sos.close();
    }


    /**
     * ajax检查验证码是否正确
     * @param code
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/checkCode")
    public String checkCode(String code, HttpServletRequest request){
        Map<String, String> map = new HashMap<>();
        HttpSession session = request.getSession();

        if(code.equalsIgnoreCase(session.getAttribute("codeStr").toString())){
            map.put("status", "1");
        } else {
            map.put("status", "2");
        }

        String jsonStr = JSON.toJSONString(map);
        return jsonStr;
    }

}
